<template>
	<view class="j-page">

		<view style="text-align: center; margin: -60px -20px -70px -60px;">
			<image src="/static/logo2.png" />
		</view>

		<uni-forms v-if="state.recommit || state.clew_id === ''" ref="refForm" :model="state.model" label-position="left"
			border label-align="right" :rules="state.rules">

			<uni-forms-item label='姓名' name='name' style="border-top: 1px solid #e8e8e8;">
				<uni-easyinput type='text' v-model='state.model.name' placeholder='请输入姓名' :maxlength="5" />
			</uni-forms-item>
			<uni-forms-item label='手机号' name='contact_info' required>
				<uni-easyinput type='text' v-model='state.model.contact_info' placeholder='请输入手机号' :maxlength="11" />
			</uni-forms-item>
			<uni-forms-item label='性别' name='gender'>
				<uni-data-checkbox v-model="state.model.gender"
					:localdata="[{text: '男',value: '男'}, {text: '女',value: '女'}]"></uni-data-checkbox>
			</uni-forms-item>
			<!-- <uni-forms-item label='毕业学校' name='graduation_school'>
				<uni-easyinput type='text' v-model='state.model.graduation_school' placeholder='请输入毕业学校' :maxlength="20" />
			</uni-forms-item> -->
			<!-- <uni-forms-item label='身份证号' name='id_number'>
				<uni-easyinput type='text' v-model='state.model.id_number' placeholder='请输入身份证号' :maxlength="18" />
			</uni-forms-item> -->

			<uni-forms-item label='预约到校日期' name='invite_date'>
				<uni-datetime-picker type="date" v-model="state.model.invite_date" placeholder='请选择预约到校日期'
					:start="state.invite_date_min" :end="state.invite_date_max" />
			</uni-forms-item>


			<uni-forms-item label='信息来源' name='source_from'>
				<!-- <uni-combox :candidates="state.source_list" placeholder="您从什么地方知道我们学校的"
					v-model="state.model.source_from"></uni-combox> -->
				<uni-data-select v-model="state.model.source_from" :localdata="state.source_list"
					placeholder="您从什么地方知道我们学校的"></uni-data-select>
			</uni-forms-item>
			<!-- <uni-forms-item label='家庭地址' name='family_address'>
				<uni-easyinput type='text' v-model='state.model.family_address' placeholder='请输入家庭地址' />
			</uni-forms-item> -->


			<uni-forms-item label='咨询老师' name='teacher'>
				<text class="j-data">{{state.options.action_by}}</text>
			</uni-forms-item>
			<uni-forms-item label='咨询电话' name='teacher'>
				<view style="display: flex; flex-direction: column; padding-left: 10px; gap: 5px;">
					<!-- <text class="j-data">{{state.options.mobile}}</text> -->
					<!-- <text v-if="state.options.action_id_by==='12096419491178140'" class="j-data">132 0521 8899</text>
					<text v-if="state.options.action_id_by==='12096419491178140'" class="j-data">132 0527 8899</text>
					<text v-if="state.options.action_id_by==='12096419491178140'" class="j-data">051088651198</text> -->

					<view v-if="state.options.action_id_by==='12096419491178140'" class="j-mobile">
						<text v-for="ii in '13205218899'.split('')">{{ii}}</text>
					</view>
					<view v-if="state.options.action_id_by==='12096419491178140'" class="j-mobile">
						<text v-for="ii in '13205278899'.split('')">{{ii}}</text>
					</view>
					<view v-if="state.options.action_id_by==='12096419491178140'" class="j-mobile">
						<text v-for="ii in '051088651198'.split('')">{{ii}}</text>
					</view>
				</view>
			</uni-forms-item>
			<!-- <uni-forms-item label='附件' name='extra'>

				<view style="display: flex; align-items: center; flex-wrap: wrap;">
					<view v-for="(ii,i) in state.thumbnailList" class="j-image-wrap" :key="ii">
						<image class="j-fault-image" :src="getImageUrl(ii)" mode="aspectFit" @click="toPreviewImage(i)"></image>
						<view style="position: absolute; right: -7px; top: -15px;" @click="toRemoveImage(i)">
							<uni-icons type="clear" size="24"></uni-icons>
						</view>
					</view>

					<view v-if="state.thumbnailList.length < 5" class="j-upload-btn" @click="toUploadImage">
						<uni-icons type="camera-filled" size="40" color="#c6c6c6"></uni-icons>
					</view>
				</view>

			</uni-forms-item> -->

			<uni-forms-item>
				<button type="primary" @click="submitForm">提交</button>
			</uni-forms-item>
		</uni-forms>

		<view v-else style="font-size: 20px; padding: 10px;color: brown; ">
			<p style="line-height: 32px; text-indent: 1em; margin-bottom: 5px;">
				您的报名已提交成功，我们老师会尽快和您联系。如需重新提交报名，请点击下述重新报名按钮。
			</p>
			<view style="margin-bottom: 5px;"><text>咨询老师：</text>{{state.options.action_by}} </view>

			<view style="display: flex;"><text>咨询电话：</text>
				<view v-if="state.options.action_id_by==='12096419491178140'" class="j-mobile2">
					<text v-for="ii in '13205218899'.split('')">{{ii}}</text>
				</view>
			</view>
			<view style="display: flex;"><text style="color: transparent;">咨询电话：</text>
				<view v-if="state.options.action_id_by==='12096419491178140'" class="j-mobile2">
					<text v-for="ii in '13205278899'.split('')">{{ii}}</text>
				</view>
			</view>
			<view style="display: flex;"><text style="color: transparent;">咨询电话：</text>
				<view v-if="state.options.action_id_by==='12096419491178140'" class="j-mobile2">
					<text v-for="ii in '051088651198'.split('')">{{ii}}</text>
				</view>
			</view>


			<button type="primary" @click="handleRecommit" style="margin-top: 15px;">重新报名</button>
		</view>
		<!-- <template v-if="false" title="FOR DEBUG">
			<view style="word-wrap: break-word;border-bottom: 1px solid #e8e8e8; margin-bottom: 5px;">
				{{state.imageList}}
			</view>

			<view style="word-wrap: break-word;border-bottom: 1px solid #e8e8e8; margin-bottom: 5px;">
				{{state.thumbnailList}}
			</view>

			<view style="word-wrap: break-word;border-bottom: 1px solid #e8e8e8; margin-bottom: 5px;">
				{{getPreviewImageUrls}}
			</view>
		</template> -->

	</view>
</template>

<script setup>
	import {
		computed,
		reactive,
		ref
	} from 'vue';

	import {
		onLoad
	} from '@dcloudio/uni-app';

	import config from '@/jk/config.js'
	import dlg from '/jk/utils/dialogs.js';
	import http from '@/jk/utils/request.js'

	import dayjs from 'dayjs';

	const refForm = ref(null)

	const state = reactive({

		clew_id: '',
		recommit: false,

		source_list: [{
				value: "抖音视频号",
				text: "抖音视频号"
			}, {
				value: "微信视频号",
				text: "微信视频号"
			}, {
				value: "小红书",
				text: "小红书"
			},
			{
				value: "老师/朋友推荐",
				text: "老师/朋友推荐"
			}, {
				value: "其他",
				text: "其他"
			},
		],

		invite_date_min: dayjs().format('YYYY-MM-DD'),
		invite_date_max: dayjs().add(6, 'day').format('YYYY-MM-DD'),

		options: {
			action_by: '',
			action_id_by: '',
			mobile: '',
		},

		imageList: [],
		thumbnailList: [],

		rules: {
			name: {
				label: '姓名',
				rules: [{
					required: false,
					errorMessage: '{label}不能为空'
				}, {
					minLength: 2,
					errorMessage: '请输入完整的{label}'
				}]
			},
			contact_info: {
				label: '手机号',
				rules: [{
					required: true,
					errorMessage: '{label}不能为空'
				}, {
					pattern: '^1[3-9]\\d{9}$',
					errorMessage: '{label}无效'
				}]
			},
			gender: {
				label: '性别',
				rules: [{
					required: false,
					errorMessage: '请选择{label}'
				}]
			},
			id_number: {
				label: '身份证号',
				rules: [{
						required: false,
						errorMessage: '请输入{label}'
					},
					{
						pattern: '^[1-9]\\d{5}(19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[\\dX]$',
						errorMessage: '{label}无效'
					}
				],
			},
			invite_date: {
				label: '预约到校日期',
				rules: [{
					required: false,
					errorMessage: '请选择{label}'
				}]
			},
			source_from: {
				label: '信息来源',
				rules: [{
					required: false,
					errorMessage: '请选择{label}'
				}]
			},
			extra: {
				label: '附件',
				rules: [{
					required: false
				}]
			}
		},

		model: {
			name: '',
			contact_info: '',
			gender: '',
			id_number: '',
			graduation_school: '',
			birth_date: '',
			family_address: '',
			extra: '',

			invite_date: '',
			source_from: '',
		}
	})


	onLoad((options) => {

		// 抓取之前填报提交成功的clew_id
		state.clew_id = uni.getStorageSync('__CLEW_ID') || '';

		state.options.action_id_by = options.id || '';
		state.options.action_by = decodeURIComponent(options.name || '');
		state.options.mobile = options.mobile || '';

	})

	// 如果url式以http开头，则直接返回，如果不是，则加上服务器根目录前缀
	const getImageUrl = (imageUrl) => {
		if (imageUrl.toLowerCase().startsWith('http')) {
			return imageUrl;
		} else {
			return config.imageRootUrl + encodeURIComponent(imageUrl);
		}
	}

	// 带  _t 后缀的文件名是 缩略图文件，需要把它替换为原图文件名
	const getPreviewImageUrls = computed(() => {
		return state.thumbnailList.map(r => {
			return getImageUrl(r.replace(/_t(?=\.)/, ''))
		})
	})

	const toUploadImage = () => {

		uni.chooseImage({
			success: (chooseImageRes) => {

				const tempFilePaths = chooseImageRes.tempFilePaths;

				if (state.thumbnailList.find(r => r === tempFilePaths[0])) {
					return;
				}

				if (chooseImageRes.tempFiles[0].size > 1024 * 1024 * 10) {
					dlg.showError('图片文件尺寸最大不超过10M')
					return;
				}

				uni.uploadFile({
					url: config.imageUploadApiUrl, //仅为示例，非真实的接口地址
					filePath: tempFilePaths[0],
					fileType: 'image',
					name: 'file',
					fromData: {},
					success: (uploadFileRes) => {
						const res = JSON.parse(uploadFileRes.data);

						if (res.code === 0) {
							state.imageList.push(res.result);
							state.thumbnailList.push(getImageUrl(res.result));
							state.model.extra = state.imageList.join(',');
						}
					},
					fail(err) {
						console.log({
							err
						})
					}
				});
			}
		});
	}

	const toRemoveImage = (index) => {
		let found = state.imageList.filter((ii, i) => i !== index);
		let found2 = state.thumbnailList.filter((ii, i) => i !== index);

		state.imageList = [...found];
		state.thumbnailList = [...found2]
		state.model.extra = state.imageList.join(',');
	}

	const toPreviewImage = (index) => {
		// 预览图片
		uni.previewImage({
			urls: getPreviewImageUrls.value,
			current: index,
			indicator: 'default',
		});
	}

	const handleRecommit = () => {
		state.recommit = true;
	}

	async function submitForm() {
		refForm.value.validate(async (err, data) => {

			if (err) {
				return;
			}
			
			console.log({data})

			data.name = data.name.trim() === '' ? '未知' : data.name;

			dlg.showConfirm('您确定要提交报名吗?', async () => {

				const ir = await http.post({
					url: '/enroll/clew/selfnew',
					data: {
						...data,

						action_by: state.options.action_by,
						action_id_by: state.options.action_id_by,
					}
				})

				console.log(3344, {
					ir
				})

				if (ir) {
					state.clew_id = ir;
					state.recommit = false;
					uni.setStorageSync('__CLEW_ID', ir);

					dlg.showToast('提交报名成功')

					state.imageList = [];
					state.thumbnailList = [];

					state.model = {
						name: '',
						contact_info: '',
						gender: '',
						id_number: '',
						birth_date: '',
						family_address: '',
						extra: '',

						invite_date: '',
						source_from: '',
					}
				}
			})

		})
	}
</script>

<style lang="scss" scoped>
	.j-page {
		box-sizing: border-box;
		height: 100vh;
		padding: 10rpx 8px;
		margin: 0;

		font-size: 16px;

		background-color: white;
		width: 750rpx;

		.j-btn-submit {
			background-color: green;
			color: white;

			&:hover {
				opacity: 75%;
			}
		}

		.j-block {
			padding: 0 8px;
			border: 1px solid #e8e8e8;
			border-radius: 2px;
			margin: 10px 0;

			background-color: white;
			box-shadow: 2px 2px 4px 0 rgba(107, 107, 107, 0.2);

			&>view:last-of-type {
				border-bottom: none;
			}

			&:nth-of-type(odd) {
				// background-color: #ffff0010;
				border: 1px solid #06e8bb1a;
			}

			&:nth-of-type(even) {
				// background-color: white;
				border: 1px solid #fc52301a;
			}
		}


		.j-row {
			padding: 16rpx 0;
			border-bottom: 1px solid #e8e8e8;

			display: flex;
			align-items: center;
			gap: 12rpx;


			.j-label,
			&>text:first-of-type {
				width: 220rpx;
				text-align: left;
				padding-left: 5px;

				font-weight: 700;
				word-wrap: break-word;

				color: rgb(96, 98, 102);

				&::after {
					content: ':';
				}

				&::before {
					content: '*';
					color: transparent;
				}
			}

			.j-required {

				&::before {
					content: '*';
					color: red;
					margin-right: 2px;
				}
			}

			.j-content,
			&>view:first-of-type {
				flex-grow: 1;
				padding-right: 5px;

				display: flex;

				&>* {
					flex-grow: 1;
				}

			}
		}

		.uni-forms-item__content>.j-data {
			padding-left: 10px;
			;
		}
	}

	.j-upload-btn {
		width: 150rpx;
		height: 150rpx;

		display: flex;
		justify-content: center;
		align-items: center;

		border: 1px solid #c6c6c6;
		border-radius: 3px;
		margin-right: 10rpx;
		margin-bottom: 10rpx;
	}

	.j-fault-image {
		width: 150rpx;
		height: 150rpx;
	}

	.j-image-wrap {
		position: relative;

		border: 1px solid #e8e8e8;
		border-radius: 3px;
		margin-right: 10rpx;
		margin-bottom: 10rpx;
	}

	.j-mobile {
		display: flex;
		width: 120px;
		justify-content: space-between;
	}

	.j-mobile2 {
		display: flex;
		width: 145px;
		justify-content: space-between;
	}
</style>